<?php
/**
*
*	注册程序 @zairwolf 
*/

require_once 'include/init.php';
require_once ROOT.'include/api.func.php';

//昵称检查
if($action=='checkreg'){
	if(!$_SYSTEM['USER']['open'] || $_G['user_id']) json(array('result'=>1));//禁止注册

	$name=_get('name');
	$email=_get('email');
	if($name){
		if(db_r("select * from rd8_user where name='$name' and active<>-99")) json(array('result'=>2));//已有用户名
		if(banList($name, 'name')) json(array('result'=>3));//禁止用户名
		if(preg_match("/\\|%|&| |\'|\"|\/|\*|,|<|>|\r|\t|\n|#/im", $name)) json(array('result'=>4));//用户名中包含非法字符
		$len = rmb_strlen($name,false);
		if($len < $_SYSTEM['USER']['minlength'] || $len > $_SYSTEM['USER']['maxlength']) json(array('result'=>5));//用户名长度非法
	}elseif($email){
		if(!preg_match("/^\w[\w\.\-\+]*@\w[\w\-]+(\.\w+)+$/", $email)) json(array('result'=>1));//该邮箱格式暂时不被接受
		if(db_r("select * from rd8_user where email='$email' and active<>-99")) json(array('result'=>2));//此邮箱已被注册
	}

	json(array());//正常
}


if(!$_SYSTEM['USER']['open'] && (!$action || in_array($action,array('reg2','reg3','verify') ))) {
	b('目前禁止注册');
}

include _config('info');


if(!$action){//注册提示问题
	$regq = db_rows("select * from rd8_regq where active=1 order by id");//注冊問題

	_header(array('注册'));
	$tpl = new T('reg_01');
	$tpl->assign('C_regq',$regq);
	$tpl->output();
	_footer();
}

if($action=='reg2'){
	$regq = db_rows("select * from rd8_regq where active=1 order by id");//注冊問題
	$a=_post('a');
	$forward=_post('forward');
	//检查问题答案
	if(empty($a)) b('请先回答注册第一步的问题');
	$i=1;
	foreach($regq as $val){
		if(!$a[$val['id']] || $a[$val['id']]<>$val['solution']){
			b("第{$i}个问题回答错误");
		}
		$i++;
	}

	_header(array('注册'));
	$tpl = new T('reg_02');
	$tpl->assign(array(
		'C_readme'   => show_text($_SYSTEM['INFO']['eula'], $_SYSTEM['INFO']['html']['eula']),
		'C_code'   =>  substr(md5($_G['user_ip'].$_SYSTEM['SAFE']['code']),0,10).base64_encode(serialize($a)),
		'forward'   => $forward,
		'minlen'    => $_SYSTEM['USER']['minlength'],
		'maxlen'    => $_SYSTEM['USER']['maxlength'],
		'C_loghashenable' => _secode(2),
	));
	$tpl->output();
	_footer();
}

if($action == 'reg3') {
	$regq = db_rows("select * from rd8_regq where active=1 order by id");//注冊問題
	$name=_post('name');
	$email=_post('email');
	$pswd=_post('pswd');
	$question=_post('question');
	$answer=_post('answer');
	$secode=_post('secode');
	$ccode=_post('ccode');
	$forward=_post('forward');
	//检查问题答案
	if(!$ccode || substr($ccode,0,10)<>substr(md5($_G['user_ip'].$_SYSTEM['SAFE']['code']),0,10)){
		b('回答问题保存错误');
	}
	$ccode=substr($ccode,10);
	$a=@unserialize(@base64_decode($ccode));
	if(empty($a)) b('请先回答注册第一步的问题');
	$i=1;
	foreach($regq as $val){
		if(!$a[$val['id']] || $a[$val['id']]<>$val['solution']){
			b("第{$i}个问题回答错误");
		}
		$i++;
	}
	if(!_secode_check(2, $secode))
		b('验证码错误');

	$len = rmb_strlen($name,false);
	if($len < $_SYSTEM['USER']['minlength'] || $len > $_SYSTEM['USER']['maxlength'])
		b('用户名长度应介于 '.$_SYSTEM['USER']['minlength'].' - '.$_SYSTEM['USER']['maxlength'].' 字符之间');

	if(preg_match("/\\|%|&| |\'|\"|\/|\*|,|<|>|\r|\t|\n|#/im", $name))
		b('用户名中含有非法字符');

	if(!preg_match("/^\w[\w\.\-\+]*@\w[\w\-]+(\.\w+)+$/", $email))
		b('请正确输入邮箱');

	//用户存在与否
	if(db_r("select * from rd8_user where name='$name' and active<>-99")) b('该用户名已被注册');
	if(db_r("select * from rd8_user where email='$email' and active<>-99")) b('该Email已被注册');

	//封禁关键词
	if(banList($name, 'name'))
		b('该用户名禁止注册');

	if(!$pswd)
		b('请填写密码');

	$cols=array(
		'name' => $name,
		'pswd'      => md5(md5($pswd)),
		'email'    => $email,
		'question'    => $question,
		'answer'    => $answer,
		'dateline' => TIMESTAMP,
		'active'   => !$_SYSTEM['USER']['verify'],
	);
	$id = db_i("insert into rd8_user set ".sqlcol($cols));
	if(!$id) b('注册数据写入失败，请联系管理员');

	//发送验证email
	if($_SYSTEM['USER']['verify']){
		$title=$_SYSTEM['SYSTEM']['SITE_NAME'].'注册验证邮件';
		$code=substr(md5($_SYSTEM['SAFE']['code'].$name.$id),0,15).$id;
		$content=show_text($_SYSTEM['INFO']['regemail'], $_SYSTEM['INFO']['html']['regemail']);
		$content=str_replace(array('[name]','[url]'), array($name,$_SYSTEM['SYSTEM']['SITE_ADDR']."/register.php?action=verify&code=$code"), $content);
		sendmail($email,$title,$content);
	}

	//登录部分
	cookie("lnfo", array($name, md5($pswd)), 3600);
	cookie("userinfo");

	if(!$forward) {
		$forward = $_SYSTEM['SYSTEM']['SITE_ADDR'];
	}else {
		$forward = urldecode($forward);
	}

	_header(array('注册'));
	$tpl = new T('reg_03');
	$target='';
	if($_SYSTEM['SYSTEM']['api'] == 'general') {//api跳转
		include _cache('api');
		$asid = GetApiData($_CACHE['api'], 'login', 'ENCODE', $name, $pswd, $email);
		$uri = ApiCache($asid);
		$target=$uri[1];
	}

	$tpl->assign('C_email',$email);
	$email=explode('@',$email);
	$tpl->assign('C_emaildomain',$email[1]);
	$tpl->assign('C_apiurl',$target);
	$tpl->output();
	_footer();

}

//发送密码
if($action=='sendpswd'){
	_header(array('忘记密码'));
	$tpl = new T('forgetpw');
		$tpl->assign(array(
			'C_readme'   => show_text($_SYSTEM['INFO']['forgetshow'], $_SYSTEM['INFO']['html']['forgetshow']),
		));
	$tpl->output();
	_footer();
}

//发送密码第二步
if($action=='sendpswd2'){
	$name=_post('name');
	$email=_post('email');
	$uinfo=db_r("select * from rd8_user where name='$name' and email='$email' and active<>-99");
	if(!$uinfo){
		b('没有此账号和邮箱的匹配记录');
	}

	_header(array('忘记密码'));
	$tpl = new T('forgetpw_02');
	$tpl->assign('luf_reg_pswdq',$uinfo['luf_reg_pswdq']);
	$tpl->assign('name',$uinfo['name']);
	$tpl->assign(array(
		'C_readme'   => show_text($_SYSTEM['INFO']['forgetshow'], $_SYSTEM['INFO']['html']['forgetshow']),
	));
	$tpl->assign('email',$uinfo['email']);
	$tpl->output();
	_footer();
		
}

//发送密码第3步
if($action=='sendpswd3'){
	$name=_post('name');
	$email=_post('email');
	$luf_reg_pwsda=_post('luf_reg_pwsda');
	$uinfo=db_r("select * from rd8_user where name='$name' and email='$email' and active<>-99");
	if(!$uinfo){
		b('没有此账号和邮箱的匹配记录');
	}
	//提交检查
	if(!empty($uinfo['luf_reg_pwsda']) && $luf_reg_pwsda<>$uinfo['luf_reg_pwsda']){
		b('密码提示答案错误');
	}

	//安全起见，设置找回时间
	db_q("update rd8_user set datelinesendpswd='".TIMESTAMP."' where id='$uinfo[id]'");
	$uinfo['datelinesendpswd']=TIMESTAMP;
	//发送重设邮件
	$url=$_SYSTEM['SYSTEM']['SITE_ADDR']."/register.php?action=resetpswd&code="._resetpswdcode($uinfo)."&name=".urlencode($name);

	$title=$_SYSTEM['SYSTEM']['SITE_NAME'].'密码重设邮件';
	$content=show_text($_SYSTEM['INFO']['forgetemail'], $_SYSTEM['INFO']['html']['forgetemail']);
	$content=str_replace(array('[name]','[url]'), array($name, $url), $content);
	sendmail($email,$title,$content);

	//提示成功信息
	_header(array('忘记密码重设邮件发送成功'));
	$tpl = new T('forgetpw_03');
	$tpl->assign(array(
		'C_readme'   => show_text($_SYSTEM['INFO']['forgetshow'], $_SYSTEM['INFO']['html']['forgetshow']),
	));
	$tpl->assign('email',$uinfo['email']);
	$tpl->output();
	_footer();
}

//重设密码
if($action=='resetpswd'){
	$name=_get_post('name');
	$code=_get_post('code');
	//检查code/name
	$uinfo=db_r("select * from rd8_user where name='$name' and active<>-99");
	if(!$uinfo){
		b('没有此账号'.$name);
	}
	if(!$code || _resetpswdcode($uinfo)<>$code){
		b('找回验证码不正确');
	}
	if($submit){
		$newpswd=_post('newpswd');
		if(!$newpswd) b('请设置密码');
		db_q("update rd8_user set pswd='".md5(md5($newpswd))."',datelinesendpswd=0 where name='$name'");
		//提示成功信息
		_header(array('重设密码成功'));
		$tpl = new T('resetpswd_02');
		$tpl->assign(array(
			'C_readme'   => show_text($_SYSTEM['INFO']['forgetshow'], $_SYSTEM['INFO']['html']['forgetshow']),
		));
		$tpl->assign('name',$name);
		$tpl->output();
		_footer();
	}else{
		_header(array('重设密码'));
		$tpl = new T('resetpswd');
		$tpl->assign(array(
			'code'	=>	$code,
			'name'	=>	$name,
			'email'	=>	$uinfo['email'],
			'C_readme'   => show_text($_SYSTEM['INFO']['forgetshow'], $_SYSTEM['INFO']['html']['forgetshow']),
		));
		$tpl->output();
		_footer();
	}
}

//用户注册的验证
if($action=='verify'){
	$code=_get('code');
	if(!$code) b('验证码空');
	$id=substr($code,15);
	if(!$id || !ris_int($id)) b('用户信息错误');
	$uinfo=db_r("select * from rd8_user where id='$id' and active<>-99");
	if(!$uinfo) b('无此信息');
	if($uinfo['active']==1) b('已经激活过');
	if(substr(md5($_SYSTEM['SAFE']['code'].$uinfo['name'].$id),0,15)<>substr($code,0,15)) b('验证码错误');
	//开始激活
	db_q("update rd8_user set active=1 where id='$id'");

	_header(array('注册验证'));
	$tpl = new T('reg_verify');
	$tpl->assign('C_name',$uinfo['name']);
	$tpl->output();
	_footer();
}


function _resetpswdcode($uinfo){
	global $_SYSTEM;
	Return md5($uinfo['dateline'].$uinfo['id'].$_SYSTEM['SAFE']['code'].$uinfo['pswd'].$uinfo['datelinesendpswd']);
}